package com.example.demo01.controller;

import com.example.demo01.Entity.Client;
import com.example.demo01.Entity.Tag;
import com.example.demo01.Service.ClientService;
import com.example.demo01.Service.TagService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
@RequestMapping("/api/tag")
public class TagController {

    @Autowired
    private TagService tagService;

    @Autowired
    private ClientService clientService;

    // 为客户添加标签
    @PostMapping("/{clientId}/add")
    public String addTagToClient(@PathVariable Long clientId, @RequestParam String labelName) {
        try {
            // 调用服务方法添加标签
            Tag tag = tagService.addTagToClient(clientId, labelName);
            return "标签添加成功: " + tag.getLabelName();
        } catch (Exception e) {
            e.printStackTrace();
            return "添加标签失败";
        }
    }

    // 获取某个客户的所有标签
    @GetMapping("/{clientId}")
    public List<Tag> getTagsByClientId(@PathVariable Long clientId) {
        return tagService.getTagsByClientId(clientId);
    }

    // 删除某个客户的所有标签
    @DeleteMapping("/{clientId}/delete")
    public String deleteTagsByClientId(@PathVariable Long clientId) {
        try {
            tagService.deleteTagsByClientId(clientId);
            return "删除标签成功";
        } catch (Exception e) {
            e.printStackTrace();
            return "删除标签失败";
        }
    }

    // 根据标签获取客户
    // 根据标签获取客户
    @GetMapping("/client")
    public String getClients(@RequestParam(value = "filter", defaultValue = "all") String filter, Model model) {
        List<Client> clients;

        // 根据过滤类型选择获取的客户
        if ("new".equals(filter)) {
            clients = tagService.getClientsByType("new");  // 获取新客户
        } else if ("old".equals(filter)) {
            clients = tagService.getClientsByType("old");  // 获取老客户
        } else {
            clients = tagService.getClientsByType("all");  // 获取所有客户
        }

        // 将客户数据传递到视图
        model.addAttribute("clients", clients);  // 客户数据
        model.addAttribute("filter", filter);  // 当前筛选条件

        // 返回到客户列表页面，并且带上筛选后的数据
        return "client";  // 返回 Thymeleaf 模板
    }


}
